package io.renren.controller;

import io.lettuce.core.dynamic.annotation.Param;
import io.renren.entity.Result;
import io.renren.entity.WxuserEntity;
import io.renren.service.WxuserService;
import io.renren.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.UUID;

/**
 * describe:
 * create @ kylin  2019/03/03
 */
@Api(tags="用户个人信息")
@RestController
@RequestMapping("/api/wxuser")
public class ApiWxUserController {

    @Autowired
    private WxuserService wxuserService;

    @ApiOperation(value="创建用户", notes="根据用户点击个人页面获取用户信息")
    @PostMapping(value = "/add")
    public Result addUser(WxuserEntity wxuserEntity) throws Exception{
        String openid = wxuserEntity.getOpenid();

        //先进行查询用户是否已经存在如果存在不许要进行添加到数据库，否则写到数据库，同时防止动态刷新后再次写入
        WxuserEntity u = wxuserService.selectOpenIdIsExist(openid);
        if (u == null){
            //如果为空,说明第一次使用，没有进行登录过，需要写入到数据库
            String uuid = UUID.randomUUID().toString();
            wxuserEntity.setUuid(uuid);
            wxuserEntity.setCreatetime(new Date());
            return ResultUtil.success(wxuserService.save(wxuserEntity)) ;
        }else{
            //说明是微信登录失效，进行刷新，数据库不需要更新，因为用户openid唯一
            return null;
        }
    }

    @ApiOperation(value="更新信息", notes="更新学生相关信息")
    @PostMapping(value = "/update")
    public Result update(@RequestParam("username") String username, @RequestParam("department") String department,
                                       @RequestParam("xuehao") String xuehao, @RequestParam("banji") String banji,
                                       @RequestParam("openid") String openid){

        WxuserEntity wxuserEntity = new WxuserEntity();
        wxuserEntity.setUsername(username);
        wxuserEntity.setDepartment(department);
        wxuserEntity.setXuehao(xuehao);
        wxuserEntity.setBanji(banji);
        wxuserEntity.setOpenid(openid);
        try {
            Integer update_code = this.wxuserService.updateInfo(wxuserEntity);
            if (update_code > 0 ){
                String uuid = this.wxuserService.RtnWxStuUuid(openid);
                return ResultUtil.success(uuid);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
